import {Helmet, Link, history, useModel} from '@umijs/max';
import {
  Alert,
  App,
  Form,
  Select,
  Tabs,
  InputNumber,
  Switch,
  Slider,
  Radio,
  Checkbox,
  Rate,
  Upload,
  Button,
  ColorPicker,
  Space,
  Row,
  Col, message, Card, Divider, Spin, List, Avatar, Result
} from 'antd';
import {createStyles} from 'antd-style';
import React, {useEffect, useState} from 'react';
import {
  genChartByAiUsingPost,
  listChartByPageUsingPost,
  listMyChartByPageUsingPost
} from "@/services/yubi/chartController";
import {undefined} from "@umijs/utils/compiled/zod";
import ReactECharts from 'echarts-for-react';
import {getInitialState} from "@/app";
import Search from "antd/es/input/Search";

const {Option} = Select;

const useStyles = createStyles(({token}) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    chartItem: {
      cursor: 'pointer',
      '&:hover': {
        boxShadow: token.boxShadow,
        transform: 'scale(1.01)',
        transition: 'all 0.3s',
      },
    },
  };
});
/**
 * 我的图表页面
 * @constructor
 */

const MyChartPage: React.FC = () => {
  const initSearchParams = {
    current: 1,
    pageSize: 8,
    sortField: 'updateTime',
    sortOrder: 'descend',

  };
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({...initSearchParams});
  const {initialState, setInitialState} = useModel('@@initialState');
  const {currentUser} = initialState ?? {};
  const [chartList, setChartList] = useState<API.Chart[]>();
  const [total, setTotal] = useState<number>();
  const [loading,setLoading]=useState<boolean>(false);
  const { styles } = useStyles(); // 添加这行来获取styles对象
  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listMyChartByPageUsingPost(searchParams);
      //隐藏图表的title
      if (res.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
        if( res.data.records) {
          res.data.records.forEach(data => {
            const chartOption = JSON.parse(data.genChart ?? '{}');
            chartOption.title = undefined;
            data.genChart = JSON.stringify(chartOption);
          });
        }
      } else {
        message.error('获取我的图表失败');
      }
    } catch (e: any) {
      message.error('获取我的图表失败' + e.message);

    }
    setLoading(false);

  };

  // Add a new function to navigate to the detail page
  const goToDetail = (id: any) => {
    history.push(`/my_chart/detail/${id}`);
  };
  useEffect(() => {
    loadData();
  }, [searchParams]);

  return (
    <div className="my-chart-page">
      <div>
        <Search placeholder="请输入图表名称"  loading={loading} enterButton  onSearch={(value)=>{
          setSearchParams(
            {...searchParams,
              name:value,
            }
          )
        }}/>
      </div>
      <div style={{marginBottom: 16}}></div>
      <List
        itemLayout="vertical"
        size="large"
        grid={{ gutter: 16, column: 2 }}
        pagination={{
          onChange: (page,pageSize) => {
            setSearchParams({...searchParams,current:page,pageSize:pageSize});
            console.log(page);
          },
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total: total,
        }}
        loading={ loading}
        dataSource={chartList}
        renderItem={(item) => (
          <Card className={styles.chartItem} onClick={() => goToDetail(item.id)}>
            <List.Item
              key={item.id}
            >
              <List.Item.Meta
                avatar={<Avatar src={currentUser && currentUser.userAvatar} />}
                title={item.name}
                description={item.chartType ? ('图表类型：' + item.chartType) :  ''}
              />

              {/*{*/}
              {/*  item.status === 'succeed' && (*/}
              {/*    <div style={{ height: 300, display: 'flex', flexDirection: 'column' }}>*/}
              {/*      <div>分析目标：{item.goal}</div>*/}
              {/*      <ReactECharts option={JSON.parse(item.genChart ?? '{}')} style={{ flex: 1 }} />*/}
              {/*    </div>*/}
              {/*  )*/}
              {/*}*/}
              {/*{*/}
              {/*  item.status === 'wait' && (*/}
              {/*    <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>*/}
              {/*      <Result*/}
              {/*        status="warning"*/}
              {/*        title="图表待生成"*/}
              {/*        subTitle={item.execMessage ?? '当前图表生成队列繁忙，请耐心等待'}*/}
              {/*        style={{ margin: 0, padding: 0 }}*/}
              {/*      />*/}
              {/*    </div>*/}
              {/*  )*/}
              {/*}*/}
              {/*{*/}
              {/*  item.status === 'running' && (*/}
              {/*    <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>*/}
              {/*      <Result*/}
              {/*        status="info"*/}
              {/*        title="图表生成中"*/}
              {/*        subTitle={item.execMessage}*/}
              {/*        style={{ margin: 0, padding: 0 }}*/}
              {/*      />*/}
              {/*    </div>*/}
              {/*  )*/}
              {/*}*/}
              {/*{*/}
              {/*  item.status === 'failed' && (*/}
              {/*    <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>*/}
              {/*      <Result*/}
              {/*        status="error"*/}
              {/*        title="图表生成失败"*/}
              {/*        subTitle={item.execMessage}*/}
              {/*        style={{ margin: 0, padding: 0 }}*/}
              {/*      />*/}
              {/*    </div>*/}
              {/*  )*/}
              {/*}*/}
              {
                item.status === 'succeed' && (
                  <div style={{ height: 300, display: 'flex', flexDirection: 'column' }}>
                    <div>分析目标：{item.goal}</div>
                    <ReactECharts option={JSON.parse(item.genChart ?? '{}')} style={{ flex: 1 }} />
                  </div>
                )
              }
              {
                item.status === 'wait' && (
                  <div style={{
                    height: 300,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '20px',
                    textAlign: 'center'
                  }}>
                    <div style={{
                      width: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: 0,
                      padding: 0
                    }}>
                      <div style={{
                        fontSize: '48px',
                        marginBottom: '16px',
                        color: '#FFA500'
                      }}>⚠️</div>
                      <div style={{
                        fontSize: '18px',
                        fontWeight: 'bold',
                        marginBottom: '8px'
                      }}>图表待生成</div>
                      <div style={{
                        fontSize: '14px',
                        color: '#666',
                        lineHeight: '1.5'
                      }}>{item.execMessage ?? '当前图表生成队列繁忙，请耐心等待'}</div>
                    </div>
                  </div>
                )
              }
              {
                item.status === 'running' && (
                  <div style={{
                    height: 300,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '20px',
                    textAlign: 'center'
                  }}>
                    <div style={{
                      width: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: 0,
                      padding: 0
                    }}>
                      <div style={{
                        fontSize: '48px',
                        marginBottom: '16px',
                        color: '#1890FF'
                      }}>ℹ️</div>
                      <div style={{
                        fontSize: '18px',
                        fontWeight: 'bold',
                        marginBottom: '8px'
                      }}>图表生成中</div>
                      <div style={{
                        fontSize: '14px',
                        color: '#666',
                        lineHeight: '1.5'
                      }}>{item.execMessage}</div>
                    </div>
                  </div>
                )
              }
              {
                item.status === 'failed' && (
                  <div style={{
                    height: 300,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '20px',
                    textAlign: 'center'
                  }}>
                    <div style={{
                      width: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: 0,
                      padding: 0
                    }}>
                      <div style={{
                        fontSize: '48px',
                        marginBottom: '16px',
                        color: '#F5222D'
                      }}>❌</div>
                      <div style={{
                        fontSize: '18px',
                        fontWeight: 'bold',
                        marginBottom: '8px'
                      }}>图表生成失败</div>
                      <div style={{
                        fontSize: '14px',
                        color: '#666',
                        lineHeight: '1.5'
                      }}>{item.execMessage}</div>
                    </div>
                  </div>
                )
              }




            </List.Item>
          </Card>

        )}
      />
      <br/>

    </div>

  );
};
export default MyChartPage;
